<template>
  <div class="income-forecast">
    <div class="contentTopTitle">
      <div class="fl">
        <div class="title">收入预估</div>
      </div>
    </div>
    <div class="operation">
      <el-form :inline="true" label-width="60px" class="formList">
        <el-form-item label="选择区域">
          <dx-cascader :area_id.sync="form.areaId" />
        </el-form-item>
        <el-form-item label="账期" label-width="60px">
          <div style="display: flex">
            <el-date-picker
              v-model="form.accMonth"
              type="month"
              placeholder="选择月"
              value-format="yyyyMM"
              style="margin-right: 15px"
              @change="selectYuGu"
            ></el-date-picker>
          </div>
        </el-form-item>
        <el-form-item label="预估日期">
          <el-select v-model="form.yuGuDate">
            <el-option
              v-for="(item, index) in yuguList"
              :label="item.label"
              :value="item.value"
              :key="index"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="产品列表">
          <el-select v-model="form.productId">
            <el-option
              v-for="(item, index) in product"
              :label="item.label"
              :value="item.value"
              :key="index"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="选择来源">
          <el-cascader
            ref="cascader"
            :options="options"
            expandTrigger="hover"
            :show-all-levels="false"
            clearable
            @change="changeHandle($event)"
            :props="{ checkStrictly: true }"
            v-model="val"
          />
        </el-form-item>

        <el-form-item label="来源明细" style="width: 24%">
          <el-switch v-model="form.showSource"></el-switch>
        </el-form-item>
        <!-- <el-form-item label="明细" style="width: 10%">
          <el-switch v-model="form.showDetail"></el-switch>
        </el-form-item> -->

        <el-form-item style="width: 42%">
          <el-button size="small" type="primary" @click="submitHandle()"
            >查询</el-button
          >
          <el-button size="small" type="orange" @click="exportExcel(false)"
            >导出</el-button
          >
          <el-button size="small" type="orange" @click="exportExcel(true)"
            >导出明细</el-button
          >
        </el-form-item>
      </el-form>
      <p class="g-unit">单位: 万元</p>
      <div class="tableBox">
        <el-table
          v-loading="tableLoading"
          :data="tableData"
          style="width: 100%"
          class="tableTh28"
          height="73vh"
          border
          :span-method="arraySpanMethod"
          stripe
          ref="table"
        >
          <el-table-column
            prop="areaName"
            width="50"
            label="区域"
          ></el-table-column>
          <el-table-column
            v-if="type1"
            prop="incomeCatgName"
            width="90"
            label="来源大类"
          ></el-table-column>
          <el-table-column
            v-if="type1"
            prop="ysIncomeName"
            width="120"
            label="子来源"
          ></el-table-column>
          <el-table-column prop="incomeCode" v-if="type1" width="90" label="来源编码">
          </el-table-column>
          <el-table-column
            v-if="type1"
            prop="incomeName"
            width="120"
            label="来源明细"
          ></el-table-column>
          <el-table-column
            prop="proName"
            width="120"
            label="产品"
          ></el-table-column>
          <el-table-column
            v-for="(item, index) in title1"
            :key="index"
            class-name="right-money"
            :prop="item.id"
            :label="item.label"
            min-width="120"
          ></el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>
<script>
import { $budgetAPI } from "@/api";
import { getSessionStorage } from "@/common/js/storage";
import { getCookie } from "@/common/js/cookie";
import { createSpanTrend } from "@/utils/mixin.js";
import prefixAPI from "@/api/prefixAPI";
import { mergeSpan } from "@/utils/mixin";
import { _debounce } from "@/utils/common.js";

let id = 0;
export default {
  data() {
    return {
      form: {
        accMonth: "",
        areaId: "",
        catgName: "",
        catgNameChild: "",
        productId: "",
        showDetail: false,
        showSource: false,
        yuGuDate: "",
        checkList: [
          { index: "1", value: "来源大类" },
          { index: "2", value: "子来源" },
          { index: "3", value: "来源明细" },
        ],
      },
      yuguList: [
        {
          label: "全部",
          value: "",
        },
      ],
      checkList: [],
      isLoading: false,
      showRight: false,
      areaList: [],
      forecastOption: [],
      tableData: [],
      currentMonth: [],
      lastMonth: [],
      tableLoading: false,
      title1: [],
      sourceList: [
        {
          label: "全部",
          value: "",
        },
      ],
      sourceListChild: [
        {
          label: "全部",
          value: "",
        },
      ],
      parentSource: "",
      product: [
        {
          label: "全部",
          value: "",
        },
      ],
      spanArr: [],
      type1: false,
      val: ["0"],
      sourceValue: "0",
      incomeCode: "0",
      incomeLvl: "1",
      options: [],
    };
  },
  mounted() {
    var that = this;
    //获取到城市信息
    this.getFaceResult();
  },
  created() {
    // this.form.accMonth = this.moment().format('YYYYMM');
    this.accountInfo = JSON.parse(getSessionStorage("accountInfo"));
    this.form.areaId = this.accountInfo.areaId;
    // this.getFcDate();
    // this.getMaxAcctMonthByIncomeForecast().then(result => {
    //    console.log(result);
    // })
  },
  // mounted(){},
  methods: {
    async getFaceResult() {
      let acctMonth = await this.getMaxAcctMonthByIncomeForecast();
      let sourceList = [];
      let product = await this.getProductList();
      let tree = await this.getSourceTree();
      this.parentSource = sourceList[this.form.catgName] || "";
      this.options = tree;
      let params = {
        areaId: this.form.areaId,
        //  fcDate: fcDate,
        acctMonth: acctMonth,
        incomeCode: "0",
        incomeLvl: "1",
        indexId: this.form.productId, // 产品 id
        yuGuDate: this.form.yuGuDate,
        showSource: "0",
        showDetail: Number(this.form.showDetail),
      };
      // this.getSourceListChild(sourceList[this.form.catgName]);
      this.listTrendData(params);
    },
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      if (
        columnIndex == 0 ||
        columnIndex == 1 ||
        columnIndex == 2 ||
        columnIndex == 3 ||
        columnIndex == 4
      ) {
        return this.spanArr[rowIndex][columnIndex];
      }
    },
    selectYuGu(val) {
      var that = this;

      $budgetAPI.estimeatYuGuTime(
        {
          acctMonth: val,
        },
        (res) => {
          (that.yuguList = [
            {
              label: "全部",
              value: "",
            },
          ]),
            res.content.map((it) => {
              var obj = {
                value: it,
                label: it,
              };
              that.yuguList.push(obj);
            });
        },
        (err) => {
          console.log(err);
        }
      );
      console.log(val);
    },
    selectChanged(val) {
      var name;
      if (val === "") {
        name = "";
      } else {
        name = this.sourceList[val + 1].label;
      }
      this.getSourceListChild(name);
    },

    ///获取收入列表
    listTrendData(params) {
      let that = this;
      //  areaId:'150',
      //  fcDate:'14',
      //  accMonth:'201911'
      this.tableLoading = true;
      $budgetAPI.estimate(
        params,
        (res) => {
          this.tableLoading = false;
          this.alertError(res);
          if (res.code == 0) {
            that.title1 = [];
            let content = res.content.data;
            let titles = res.content.titles;
            let typeTitle;
            that.type1 = false;
            if (!!this.form.showSource) {
              typeTitle = [
                "areaName",
                "incomeCatgName",
                "ysIncomeName",
                "incomeCode",
                "incomeName",
              ];
              that.type1 = true;
            } else {
              typeTitle = ["areaName"];
              that.type1 = false;
            }

            this.spanArr = that.mergeSpan2(content, typeTitle);

            content.map((it) => {
              it.dataList.map((item, i) => {
                it["index" + item.fcDate] = item.indexValue;
              });
            });
            titles.map((it) => {
              let obj = {
                id: "index" + it,
                label: it,
              };
              that.title1.push(obj);
            });
            that.tableData = content;
            this.$nextTick(() => {
              this.$refs.table.doLayout();
            });
            //   this.currentMonth = this.classify(
            //     res.content.colList,
            //     "broadClass"
            //   );
            //   this.lastMonth = this.classify(
            //     res.content.preColList,
            //     "broadClass"
            //   );
            //   setTimeout(() => {
            //     this.$refs.table.doLayout();
            //   }, 500);
          }
        },
        (err) => {
          this.tableLoading = false;
        }
      );
    },
    mergeSpan2(tableData, arr) {
      let spanArr = new Array(tableData.length);
      for (let m = 0; m < spanArr.length; m++) {
        spanArr[m] = new Array(arr.length);
      }
      arr.forEach((ele, ind) => {
        let pos = null;
        tableData.forEach((item, index, self) => {
          if (index == 0) {
            spanArr[index][ind] = {
              rowspan: 1,
              colspan: 1,
            };
            pos = 0;
          } else {
            if (ele == "incomeCatgName") {
              if (
                item[ele] === self[index - 1][ele] &&
                item["areaName"] == self[index - 1]["areaName"]
              ) {
                spanArr[pos][ind].rowspan += 1;
                spanArr[index][ind] = {
                  rowspan: 0,
                  colspan: 0,
                };
              } else {
                pos = index;
                spanArr[index][ind] = {
                  rowspan: 1,
                  colspan: 1,
                };
              }
            } else {
              if (item[ele] === self[index - 1][ele]) {
                spanArr[pos][ind].rowspan += 1;
                spanArr[index][ind] = {
                  rowspan: 0,
                  colspan: 0,
                };
              } else {
                pos = index;
                spanArr[index][ind] = {
                  rowspan: 1,
                  colspan: 1,
                };
              }
            }
          }
        });
      });
      return spanArr;
    },
    checkedType(val) {
      console.log(val);
      this.checkList = val;
    },
    submitHandle: _debounce(function () {
      let params = {
        areaId: this.form.areaId,
        acctMonth: this.form.accMonth,
        indexId: this.form.productId, // 产品 id
        yuGuDate: this.form.yuGuDate,
        showSource: Number(this.form.showSource),
        showDetail: Number(this.form.showDetail),
        incomeCode: this.incomeCode,
        incomeLvl: this.incomeLvl,
      };

      this.listTrendData(params);
    }, 300),
    exportExcel(detail) {
      let token = getCookie("token");
      let indexId = this.form.productId;
      let yuGuDate = this.form.yuGuDate,
        showDetail = detail ? Number(detail) : "0";
      // 根据不同模式切换不同的路径
      if (process.env.NODE_ENV == "development") {
        window.location.href =
          prefixAPI.loc +
          "/api/yuGu/export?areaId=" +
          this.form.areaId +
          "&acctMonth=" +
          this.form.accMonth +
          "&incomeCode=" +
          this.incomeCode +
          "&incomeLvl=" +
          this.incomeLvl +
          "&indexId=" +
          indexId +
          "&showSource=" +
          Number(this.form.showSource) +
          "&yuGuDate=" +
          yuGuDate +
          "&showDetail=" +
          showDetail +
          "&token=" +
          token;
      } else if (process.env.NODE_ENV == "production") {
        window.location.href =
          prefixAPI.hp +
          "/api/yuGu/export?areaId=" +
          this.form.areaId +
          "&acctMonth=" +
          this.form.accMonth +
          "&incomeCode=" +
          this.incomeCode +
          "&incomeLvl=" +
          incomeLvl +
          "&indexId=" +
          indexId +
          "&showSource=" +
          Number(this.form.showSource) +
          "&yuGuDate=" +
          yuGuDate +
          "&showDetail=" +
          showDetail +
          "&token=" +
          token;
      }
    },
    getSourceList() {
      var that = this;
      return new Promise((resolve) => {
        $budgetAPI.getIncomeSourceTree(
          {},
          (res) => {
            console.log(res);

            // res.content.map((it, i) => {
            //   var obj = {
            //     value: i,
            //     label: it,
            //   };
            //   that.sourceList.push(obj);
            // });
            resolve(res.content);
          },
          (err) => {
            console.log(err);
          }
        );
      });
    },
    getSourceListChild(val) {
      var that = this;

      $budgetAPI.estimeatSourceChild(
        {
          catgName: val,
        },
        (res) => {
          res.content.map((it, i) => {
            var obj = {
              value: it.ysIncomeCode,
              label: it.ysIncomeName,
            };
            that.sourceListChild.push(obj);
          });
        },
        (err) => {
          console.log(err);
        }
      );
    },
    getProductList() {
      var that = this;

      return new Promise((resolve) => {
        $budgetAPI.estimeatProductList(
          {},
          (res) => {
            res.content.map((it, i) => {
              var obj = {
                value: it.indexId,
                label: it.indexName,
              };
              that.product.push(obj);
            });
            resolve(res.content);
          },
          (err) => {
            console.log(err);
          }
        );
      });
    },
    getMaxAcctMonthByIncomeForecast() {
      var that = this,
        yList = [];
      return new Promise((resolve) => {
        $budgetAPI.estimateMonth(
          {},
          (res) => {
            if (res && res.code == 0) {
              that.form.accMonth = res.content.maxAcctMonth;
              yList = res.content.yuGuDateList;
              yList.map((it) => {
                var obj = {
                  value: it,
                  label: it,
                };
                that.yuguList.push(obj);
              });
              resolve(res.content.maxAcctMonth);
            }
          },
          (err) => {}
        );
      });
    },
    getFcDate() {
      var that = this;
      return new Promise((resolve) => {
        $budgetAPI.getFcDate(
          {},
          (res) => {
            that.alertError(res);
            if (res && res.code == 0) {
              that.forecastOption = res.content;
              that.form.fcDate = res.content[0].fcDate;
              resolve(res.content[0].fcDate);
            }
          },
          (err) => {}
        );
      });
    },
    changeHandle(event) {
      if (event) {
        let arr = event.slice(0);
        let value = arr.pop();

        let data = this.$refs.cascader.getCheckedNodes()[0]
          ? this.$refs.cascader.getCheckedNodes()[0].data
          : "";
        if (data) {
          this.incomeCode = data.value;
          this.incomeLvl = data.incomeLvl;
        }
        this.$refs.cascader.dropDownVisible = false;
      }
    },
    getSourceTree() {
      let that = this;
      return new Promise((resolve) => {
        $budgetAPI.getIncomeSourceTree(
          {},
          (res) => {
            let option = [],
              data = res.content.childrenList;
            data.map((item) => {
              item.value = item.incomeCode;
              item.label = item.incomeName;
              item.childrenList.map((it) => {
                it.value = it.incomeCode;
                it.label = it.incomeName;
                it.childrenList.map((it1) => {
                  it1.value = it1.incomeCode;
                  it1.label = it1.incomeName;
                });
                it.children = it.childrenList;
              });
              item.children = item.childrenList;
            });
            option[0] = {
              value: "0",
              label: "全部",
              children: data,
              incomeLvl: "1",
            };
            // res.content.map((it, i) => {
            //   var obj = {
            //     value: it.indexId,
            //     label: it.indexName,
            //   };
            //   that.product.push(obj);
            // });
            resolve(option);
          },
          (err) => {
            console.log(err);
          }
        );
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.operation {
}
.income-forecast {
  th.first-column {
    text-align: center !important;
  }

  .first-column {
    text-align: left;

    span {
      padding-left: 16px;
    }
  }

  span.boldFont {
    padding: 0;
    font-weight: bold;
  }

  .daochu {
    float: right;

    .el-form-item__content {
      float: right;

      .el-button {
        float: right;
      }
    }
  }

  .forecast-content {
    // border: 1px solid #bbb;
    height: 67vh;
    overflow: scroll;

    .left-wrap {
      float: left;
      width: 200px;
      height: 600px;
      // background-image: url("~@/assets/images/yugu.jpg");
    }

    .right-wrap {
      margin-left: 200px;
      height: 600px;
      // background-image: url("~@/assets/images/yugu1.jpg");
    }
  }
}
/deep/ .el-table .cell {
  text-align: center;
}
</style>
